/*
 * @Author: 2678187122@qq.com
 * @Date: 2023-09-05 14:37:24
 * @LastEditTime: 2023-12-11 16:15:23
 * @LastEditors: 2678187122@qq.com
 * @Description: vuex配置js
 * @FilePath: \zykj_web\src\store\modules\settings.js
 */
import { all } from '@/api/system/data-dict'
import { globalAll, sysAll } from '@/api/system/sys-config-domain'
import settings from '@/settings'
const { title, showSettings, tagsView, sidebarLogo, fixedHeader } = settings

const state = {
  title: title,
  logo: '',
  baseUrl: 'http://127.0.0.1:8101',
  theme: localStorage.getItem('theme') || '#13C2C2',
  showSettings: showSettings,
  tagsView: tagsView,
  fixedHeader: fixedHeader,
  sidebarLogo: sidebarLogo,
  dictItem: {},
  funs: null,
  globalData: null
}

const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  }
}

const actions = {
  changeSetting({ commit }, data) {
    // const { key, value } = data
    // localStorage.setItem(key, value)
    commit('CHANGE_SETTING', data)
  },
  globalSettings({ dispatch }) {
    return new Promise((resolve, reject) => {
      // 获取全局配置
      globalAll().then(res => {
        if (!res.data || !res.data.length) resolve()
        const global = res.data.reduce((row, { code, value }) => {
          row[code] = value
          return row
        }, {})
        dispatch('changeSetting', { key: 'globalData', value: global })
        // 若字典全局配置不等于1则全查字典
        if (global['data_dict_get_way'] !== '1') {
          all().then(response => {
            dispatch('changeSetting', { key: 'dictItem', value: response.data })
            resolve(response)
          }).catch(err => {
            reject(err)
          })
        } else {
          resolve(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取系统配置
  systemSettings({ commit }) {
    sysAll().then(res => {
      if (res.data && res.data.length) {
        const sys = res.data.reduce((row, { code, value }) => {
          row[code] = value
          return row
        }, {})
        // 系统配置标题
        if (sys['system_name']) {
          commit('CHANGE_SETTING', { key: 'title', value: sys['system_name'] })
        }
        // 系统配置logo
        if (sys['system_logo']) {
          commit('CHANGE_SETTING', { key: 'logo', value: sys['system_logo'] })
        }
        // 图片路径前缀
        if (sys['system_base_url']) {
          commit('CHANGE_SETTING', { key: 'baseUrl', value: sys['system_base_url'] })
        }
      }
    })
  },
  // 单页面函数配置
  funsSetting({ dispatch, commit }, rows) {
    const modules = import.meta.globEager('@/api/**/*.js')
    const path = rows.meta.port
    dispatch('changeSetting', { key: 'funs', value: path ? modules['/src/api' + path + '.js'] : null })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

